<template>
  <div class="debug-container">
    <h1>🔌 SignalR 连接调试工具</h1>
    
    <div class="debug-status">
      <p>连接状态: <span :class="{ 'status-connected': isConnected, 'status-disconnected': !isConnected }">
        {{ isConnected ? '已连接' : '未连接' }}
      </span></p>
      <p>API URL: {{ apiUrl }}</p>
      <p>Hub URL: {{ hubUrl }}</p>
    </div>
    
    <div class="debug-controls">
      <button @click="testConnection" :disabled="isConnecting" class="debug-button">
        {{ isConnecting ? '连接中...' : '测试连接' }}
      </button>
      <button @click="testCreateRoom" :disabled="!isConnected || isConnecting" class="debug-button">
        测试创建房间
      </button>
      <button @click="testJoinRoom" :disabled="!isConnected || isConnecting" class="debug-button">
        测试加入房间
      </button>
      <button @click="clearLogs" class="debug-button">
        清空日志
      </button>
    </div>
    
    <div class="room-input" v-if="showRoomInput">
      <input v-model="roomIdInput" placeholder="输入房间名称" class="room-input-field" />
      <input v-model="customRoomIdInput" placeholder="自定义房间ID（可选）" class="room-input-field" />
    </div>
    
    <div class="debug-logs">
      <h3>📋 调试日志</h3>
      <div class="logs-container">
        <div v-for="(log, index) in logs" :key="index" :class="log.type">
          {{ log.time }} - {{ log.message }}
          <div v-if="log.details" class="log-details">{{ log.details }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { socketService } from '@/services/socketService'

const isConnected = ref(false)
const isConnecting = ref(false)
const showRoomInput = ref(false)
const roomIdInput = ref('')
const customRoomIdInput = ref('')
const logs = ref([])

// 组件挂载时初始化连接
onMounted(() => {
  console.log('SocketDebug组件挂载，初始化Socket连接...')
  socketService.initialize()
  
  // 定期检查连接状态
  const checkConnectionInterval = setInterval(() => {
    isConnected.value = socketService.isConnected
  }, 1000)
  
  // 组件卸载时清理定时器
  onUnmounted(() => {
    clearInterval(checkConnectionInterval)
  })
})

const apiUrl = computed(() => import.meta.env.VITE_API_URL || 'http://localhost:5258')
const hubUrl = computed(() => `${apiUrl.value}/hubs/game`)

// 添加日志
const addLog = (message, type = 'info', details = null) => {
  const timestamp = new Date().toLocaleTimeString()
  logs.value.push({ time: timestamp, message, type, details })
  // 限制日志数量，保持性能
  if (logs.value.length > 100) {
    logs.value.shift()
  }
  // 自动滚动到底部
  setTimeout(() => {
    const logsContainer = document.querySelector('.logs-container')
    if (logsContainer) {
      logsContainer.scrollTop = logsContainer.scrollHeight
    }
  }, 100)
}

// 测试连接
const testConnection = async () => {
  addLog('开始测试SignalR连接...')
  isConnecting.value = true
  
  try {
    // 使用已有的socketService进行连接测试
    addLog(`API URL: ${apiUrl.value}`, 'info')
    addLog(`Hub URL: ${hubUrl.value}`, 'info')
    
    // 调用initialize方法确保连接已创建
    socketService.initialize()
    
    // 等待一下，让连接有时间建立
    setTimeout(() => {
      const currentStatus = socketService.isConnected
      addLog(`当前连接状态: ${currentStatus ? '已连接' : '未连接'}`, currentStatus ? 'success' : 'warning')
      isConnected.value = currentStatus
      isConnecting.value = false
    }, 2000)
    
  } catch (error) {
    addLog(`连接测试失败: ${error.message || error}`, 'error')
    console.error('连接测试错误:', error)
    isConnecting.value = false
  }
}

// 测试创建房间
const testCreateRoom = async () => {
  if (!roomIdInput.value) {
    addLog('请输入房间名称', 'warning')
    return
  }
  
  try {
    const roomName = roomIdInput.value
    const customId = customRoomIdInput.value.trim() || null
    
    if (customId) {
      addLog(`尝试创建房间: ${roomName} (自定义ID: ${customId})`, 'info')
    } else {
      addLog(`尝试创建房间: ${roomName} (系统自动生成ID)`, 'info')
    }
    
    // 使用已有的socketService进行房间创建，传入自定义ID（如果有）
    const result = await socketService.createRoom(roomName, customId)
    addLog(`房间创建成功！游戏ID: ${result?.room?.id || '未知'}`, 'success')
    // 保存房间ID以便测试加入
    roomIdInput.value = result?.room?.id || ''
    customRoomIdInput.value = ''
  } catch (error) {
    addLog(`创建房间失败: ${error.message}`, 'error')
    console.error('创建房间错误:', error)
  }
}

// 测试加入房间
const testJoinRoom = async () => {
  if (!roomIdInput.value.trim()) {
    showRoomInput.value = true
    addLog('请输入房间ID', 'warning')
    return
  }
  
  try {
    addLog(`尝试加入房间: ${roomIdInput.value}`, 'info')
    
    // 使用已有的socketService进行房间加入
    const result = await socketService.joinRoom(roomIdInput.value)
    addLog(`加入房间成功！玩家ID: ${result?.playerId || '未知'}`, 'success')
  } catch (error) {
    addLog(`加入房间失败: ${error.message}`, 'error')
    console.error('加入房间错误:', error)
  }
}

// 清空日志
const clearLogs = () => {
  logs.value = []
  addLog('日志已清空')
}

// 在组件挂载时检查环境
addLog('调试工具已加载')
addLog(`当前环境: VITE_API_URL = ${apiUrl.value}`)
addLog(`Hub URL: ${hubUrl.value}`)

// 组件卸载时的清理
onUnmounted(() => {
  // 清理可能的资源
})
</script>

<style scoped>
.debug-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background: var(--surface);
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-md);
}

h1 {
  color: var(--primary);
  margin-bottom: 20px;
  text-align: center;
}

h3 {
  color: var(--text-primary);
  margin-top: 20px;
  margin-bottom: 10px;
}

.debug-status {
  background: rgba(255, 255, 255, 0.05);
  padding: 15px;
  border-radius: var(--radius);
  margin-bottom: 20px;
}

.debug-status p {
  margin: 5px 0;
  color: var(--text-muted);
}

.status-connected {
  color: var(--success);
  font-weight: bold;
}

.status-disconnected {
  color: var(--destructive);
  font-weight: bold;
}

.debug-controls {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.debug-button {
  background: var(--primary);
  color: white;
  border: none;
  padding: 10px 15px;
  border-radius: var(--radius);
  cursor: pointer;
  transition: var(--transition);
}

.debug-button:hover:not(:disabled) {
  background: var(--primary-hover);
  transform: translateY(-1px);
}

.debug-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.room-input {
  margin-bottom: 20px;
}

.room-input-field {
  width: 100%;
  padding: 10px;
  border: 1px solid var(--border);
  border-radius: var(--radius);
  background: rgba(255, 255, 255, 0.05);
  color: var(--text-primary);
}

.debug-logs {
  max-height: 400px;
  overflow: auto;
  border: 1px solid var(--border);
  border-radius: var(--radius);
  background: rgba(255, 255, 255, 0.02);
}

.logs-container {
  padding: 10px;
  font-family: monospace;
  font-size: 14px;
}

.logs-container > div {
  margin-bottom: 5px;
  padding: 5px;
  border-radius: 4px;
}

.info {
  color: var(--text-primary);
}

.success {
  background: rgba(34, 197, 94, 0.1);
  color: var(--success);
}

.warning {
  background: rgba(251, 191, 36, 0.1);
  color: var(--warning);
}

.error {
  background: rgba(239, 68, 68, 0.1);
  color: var(--destructive);
}

.log-details {
  font-size: 12px;
  margin-top: 5px;
  padding-left: 20px;
  opacity: 0.8;
}
</style>